﻿using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TicketMLib;

namespace TicketsOps
{
    public class TicketsOps
    {
        ArrayList assigneeList;
        ArrayList efforts;
        int ctr;
        #region Tickets related operations
        /// <summary>
        /// This method gets all the tickets from a team project and converts their ID and Title in a DataTable which is then returned. 
        /// </summary>
        /// <param name="sProject">Session variable that stores the selected project and passed from page to this method</param>
        /// <returns></returns>
        public DataTable GetTickets(string sProject)
        {
            DataTable TicketsTable = new DataTable();
            DataColumn PkTicketIdColumn = TicketsTable.Columns.Add("TicketId", typeof(System.Int32));
            TicketsTable.Columns.Add("TicketTitle", typeof(string));
            try
            {
                #region Get Variable Values from existing config file
                string uName;
                string passwd;
                string domain;
                string tfs;
                string collection;
                string _project;
                Utils.SetGenVarValues(sProject, out uName, out passwd, out domain, out tfs, out collection, out _project);
                #endregion

                TfsTeamProjectCollection tpc = Utils.Connect2Tfs(uName, passwd, domain, tfs, collection);

                WorkItemStore wiStore = tpc.GetService<WorkItemStore>();
                
                WorkItemCollection wiColl = wiStore.Query("SELECT [System.Id], [System.Title] FROM WorkItems WHERE [System.TeamProject] = '" + _project + "'  AND  [System.WorkItemType] = 'Ticket'");
                foreach (WorkItem wi in wiColl)
                {
                    DataRow TicketRow = TicketsTable.NewRow();
                    TicketRow["TicketId"] = wi.Id;
                    TicketRow["TicketTitle"] = wi.Title;
                    TicketsTable.Rows.Add(TicketRow);
                }
            }
            catch
            {

            }

            return TicketsTable;
        }



        /// <summary>
        /// This method gets a ticket by its ID and adds the details into a table which is then returned
        /// </summary>
        /// <param name="id">Ticket ID passed by the calling page</param>
        /// <param name="sProject">Project Name passed by the calling page.</param>
        /// <returns></returns>
        public DataTable GetTicket(int id, string sProject)
        {
            DataTable TicketTable = new DataTable();
            TicketTable.Columns.Add("ID", typeof(System.Int32));
            TicketTable.Columns.Add("State", typeof(string));
            TicketTable.Columns.Add("Assigned To", typeof(string));
            TicketTable.Columns.Add("Description", typeof(string));

            try
            {
                #region Get Variable Values from existing config file
                string uName;
                string passwd;
                string domain;
                string tfs;
                string collection;
                string _project;
                Utils.SetGenVarValues(sProject, out uName, out passwd, out domain, out tfs, out collection, out _project);
                #endregion

                TfsTeamProjectCollection tpc = Utils.Connect2Tfs(uName, passwd, domain, tfs, collection);
                WorkItemStore wiStore = tpc.GetService<WorkItemStore>();
                WorkItem wi = wiStore.GetWorkItem(id);

                DataRow fldRow1 = TicketTable.NewRow();
                fldRow1["ID"] = wi.Id;
                fldRow1["State"] = wi.State;
                fldRow1["Assigned To"] = wi.Fields["System.AssignedTo"].Value.ToString();
                fldRow1["Description"] = wi.Description;
                TicketTable.Rows.Add(fldRow1);


            }
            catch
            {

            }
            return TicketTable;

        }

        /// <summary>
        /// This method takes a ticket ID and computes the time (in minutes) spent by each team member on that ticket
        /// </summary>
        /// <param name="id">Ticket ID passed by the calling page</param>
        /// <param name="sProject">Project Name passed by the calling page.</param>
        /// <returns></returns>
        public DataTable GetEfforts(int id, string sProject)
        {

            DataTable EffortsTable = new DataTable();
            EffortsTable.Columns.Add("Name", typeof(string));
            EffortsTable.Columns.Add("Efforts", typeof(System.Int32));
            try
            {
                #region Get Variable Values from existing config file
                string uName;
                string passwd;
                string domain;
                string tfs;
                string collection;
                string _project;
                Utils.SetGenVarValues(sProject, out uName, out passwd, out domain, out tfs, out collection, out _project);
                #endregion

                TfsTeamProjectCollection tpc = Utils.Connect2Tfs(uName, passwd, domain, tfs, collection);
                WorkItemStore wiStore = tpc.GetService<WorkItemStore>();
                WorkItem wi = wiStore.GetWorkItem(id);
                RevisionCollection revColl = wi.Revisions;
                Revision LastRev = null;
                foreach (Revision rev in revColl)
                {
                    LastRev = rev;
                }

                assigneeList = new ArrayList();
                efforts = new ArrayList();
                foreach (Revision rev in revColl)
                {
                    if (rev.Fields["System.AssignedTo"].Value.ToString() != rev.Fields["System.AssignedTo"].OriginalValue.ToString() && rev.Fields["System.AssignedTo"].OriginalValue.ToString() != "")
                    {

                        if (IsAssigneePresent(rev.Fields["System.AssignedTo"].OriginalValue.ToString()))
                        {
                            int eff = 0;
                            eff = Int32.Parse(efforts[ctr].ToString());
                            eff += Int32.Parse(rev.Fields["SSGS.MyEfforts"].Value.ToString());
                            efforts[ctr] = eff;
                        }
                        else
                        {
                            assigneeList.Add(rev.Fields["System.AssignedTo"].OriginalValue.ToString());
                            efforts.Add(Int32.Parse(rev.Fields["SSGS.MyEfforts"].Value.ToString()));
                        }
                    }
                }
                for (int i = 0; i < assigneeList.Count; i++)
                {
                    DataRow AssigneeRow = EffortsTable.NewRow();
                    AssigneeRow["Name"] = assigneeList[i].ToString();
                    AssigneeRow["Efforts"] = efforts[i].ToString();
                    EffortsTable.Rows.Add(AssigneeRow);
                }
            }
            catch
            {

            }
            return EffortsTable;
        }
        private bool IsAssigneePresent(string assignee)
        {
            bool assigneePresent = false;
            ctr = 0;
            if (assigneeList != null)
            {
                foreach (string candidate in assigneeList)
                {
                    if (candidate == assignee)
                    {
                        assigneePresent = true;
                        break;
                    }
                    ctr++;
                }
            }
            return assigneePresent;
        }
        public bool DeleteTicket(int id, string sProject)
        {
            #region Get Variable Values from existing config file
            string uName;
            string passwd;
            string domain;
            string tfs;
            string collection;
            string _project;
            Utils.SetGenVarValues(sProject, out uName, out passwd, out domain, out tfs, out collection, out _project);
            #endregion

            TfsTeamProjectCollection tpc = Utils.Connect2Tfs(uName, passwd, domain, tfs, collection);
            WorkItemStore wiStore = tpc.GetService<WorkItemStore>();
            int[] ids = new int[] { id };
            IEnumerable<WorkItemOperationError> Errors;
            Errors = wiStore.DestroyWorkItems(ids);
            List<WorkItemOperationError> errorList = new List<WorkItemOperationError>(Errors);
            if (errorList.Count > 0) return false;
            else return true;
        }

        public void CopyTicket(int id, string sProject, string dProject)
        {
            #region Get Variable Values from existing config file
            string uName;
            string passwd;
            string domain;
            string tfs;
            string collection;
            string _project;
            Utils.SetGenVarValues(sProject, out uName, out passwd, out domain, out tfs, out collection, out _project);
            #endregion

            TfsTeamProjectCollection tpc = Utils.Connect2Tfs(uName, passwd, domain, tfs, collection);
            WorkItemStore wiStore = tpc.GetService<WorkItemStore>();
            WorkItem wi = wiStore.GetWorkItem(id);

            Project TargetProject = wiStore.Projects["dProject"];
            WorkItem wiCopy = new WorkItem(TargetProject.WorkItemTypes["Ticket"]);
            wiCopy.Title = wi.Title;
            wiCopy.Description = wi.Description;
            wiCopy.Save();
        }
        internal void MoveTicket(string project, string ticketId)
        {
            try
            {
                #region Get Variable Values from existing config file
                string uName;
                string passwd;
                string domain;
                string tfs;
                string collection;
                string _project;
                Utils.SetGenVarValues(project, out uName, out passwd, out domain, out tfs, out collection, out _project);
                #endregion

                TfsTeamProjectCollection tpc = Utils.Connect2Tfs(uName, passwd, domain, tfs, collection);

                WorkItemStore wiStore = tpc.GetService<WorkItemStore>();
                WorkItem wiSource = wiStore.GetWorkItem(Convert.ToInt32(ticketId));
                WorkItem wiDestination = new WorkItem(wiStore.Projects[project].WorkItemTypes["Ticket"]);
                wiDestination.Title = wiSource.Title;
                wiDestination.Description = wiSource.Description;
                wiDestination.Save();
                List<int> WI2Destroy = new List<int>();
                WI2Destroy.Add(wiSource.Id);
                wiStore.DestroyWorkItems(WI2Destroy);
            }
            catch
            {
                //Logger.CreateLogEntry("Failed to move work item " + ticketId);
            }
        }
        #endregion
    }
}
